package com.hcyy.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hcyy.dao.UserDao;
import com.hcyy.entity.Message;
import com.hcyy.entity.User;
import com.hcyy.service.UserService;
import com.hcyy.util.MD5Util;
import com.hcyy.util.UserUtil;
import com.hcyy.util.xjYanZhM;

@Controller
public class UserController {
	@Autowired
	private UserService userService;
	@Autowired
	private UserDao userDao;
	@Autowired
	private UserUtil userUtil;
	
	@RequestMapping(value="/validatelogin",method=RequestMethod.POST)
	@ResponseBody
	public Message validatelogin(User user,HttpServletRequest req){
		Message message=new Message();
		String checkcode=(String) req.getSession().getAttribute("checkcode");//session中的验证码
		if(!user.getYzm().equalsIgnoreCase(checkcode)){
			message.setMsg("验证码错误");
		}else{
			Integer sjid=Integer.parseInt(req.getParameter("sjid"));
			User user_data=userDao.findUserByUserName(user.getUsername(),sjid);
			if(user_data==null){
				message.setMsg("用户名不存在");
			}else{
				if(!user_data.getPassword().equals(MD5Util.string2MD5(user.getPassword()))){
					message.setMsg("密码错误");
				}
			}
		}
		return message;
	}
	@RequestMapping("/dologin")
	public String dologin(@ModelAttribute User user,HttpServletRequest req,Model model){
		Integer sjid=Integer.parseInt(req.getParameter("sjid"));
		if(userService.login(user,sjid)){
			req.getSession().setAttribute("user", user);
			req.getSession().setAttribute("sjid", sjid);//将sjid存入session中
			if(req.getSession().getAttribute("uri")!=null){
				String uri=(String) req.getSession().getAttribute("uri");
				if(uri.indexOf("?")<=0){
					uri = uri+"?sjid="+sjid;
				}else{
					uri = uri+"&sjid="+sjid;
				}
				req.getSession().removeAttribute("uri");
				return "redirect:"+uri;
			}else{
				return "redirect:index";
			}
		}
		return "redirect:login";
	}
	@RequestMapping("/login")
	public String login(Integer sjid,HttpServletRequest req,Model model){//sjid为请求的地址栏后缀参数
		/*if(sjid!=null){
			model.addAttribute("sjid", sjid);
		}else{
			sjid=1;//请求的sjid为null时，默认设为1（乐赛仙）
		}*/
		Integer sjid2=(Integer) req.getSession().getAttribute("sjid");//从session中获取登录存储的sjid
		if(sjid==null){//请求的sjid为null时，即地址栏不带参数
			if(sjid2!=null){//已登录
				sjid=sjid2;
			}else{//未登录
				sjid=1;//默认设为1（乐赛仙）
			}
		}
		model.addAttribute("sjid", sjid);
		if(req.getSession().getAttribute("user")!=null&&sjid.equals(sjid2)){
			return "redirect:index";//已登录，并且请求的sjid和session中存储的sjid相同
		}
		return "login";
	}
	//注销登录
	@RequestMapping("/Logout")
	public String logout(HttpServletRequest req){
		req.getSession().removeAttribute("user");
		Integer sjid=Integer.parseInt(req.getParameter("sjid"));	
		return "redirect:index?sjid="+sjid;
	}
	@RequestMapping("/Shop/User")
	public String user(HttpServletRequest request,Model model){
		User user=userUtil.findUser(request);
		String dwbh="";
		if(null!=user){
			dwbh=user.getDwbh();
		}else{
			return "redirect:login";
		}
		Integer sjid=(Integer) request.getSession().getAttribute("sjid");
		Map<String,Integer> map=userService.countOrder(dwbh, sjid);
		model.addAttribute("map",map);
		model.addAttribute("user",user);
		return "user";
	}
	
	//验证码
	@RequestMapping(value = {"/getimgyzm"}, method = { RequestMethod.POST,RequestMethod.GET})
	public void getimgyzm(HttpServletRequest request,HttpServletResponse response) throws IOException{
		//return certification code
        String strYZhM=xjYanZhM.getNumber();
//        String strYZhM=xjYanZhM.getText();
        //set session
        HttpSession session=request.getSession();
        session.setAttribute("checkcode", strYZhM);//key and value
        //getSession().put("checkcode", strYZhM);//key and value
//        BufferedImage image=xjYanZhM.getNumberImg(strYZhM);   
        BufferedImage image=xjYanZhM.getImg(strYZhM);
		response.setContentType("image/jpeg");
        //response.reset();
        OutputStream os;
        os=response.getOutputStream();
        os.flush();
        ImageIO.write(image, "jpg", os);	        
        response.flushBuffer();
        os.flush();
        os.close(); 
        os=null;
		//return "user/login";
	}
}
